import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:family_app/src/features/gallery/models/album_model.dart';
import 'package:family_app/src/features/gallery/providers/gallery_provider.dart';
import 'package:family_app/src/features/gallery/screens/album_detail_screen.dart';
import 'package:family_app/src/features/gallery/widgets/album_grid_item.dart';
import 'package:family_app/src/features/gallery/widgets/create_album_dialog.dart';
import 'package:family_app/src/theme/app_theme.dart';
import 'package:family_app/src/common/widgets/app_header.dart';

/// 相册主界面
class GalleryScreen extends ConsumerWidget {
  const GalleryScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final albumsAsync = ref.watch(albumsProvider);
    final operationState = ref.watch(albumOperationProvider);

    // 显示操作状态提示
    _showOperationMessage(context, operationState);

    return Scaffold(
      appBar: AppHeader(
        title: '相册',
        showBackButton: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () => _showCreateAlbumDialog(context, ref),
          ),
        ],
      ),
      body: albumsAsync.when(
        data: (albums) => _buildAlbumGrid(context, ref, albums),
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (error, stack) => Center(
          child: Text('加载失败: $error', style: TextStyle(color: Colors.red)),
        ),
      ),
    );
  }

  /// 构建相册网格
  Widget _buildAlbumGrid(
      BuildContext context, WidgetRef ref, List<AlbumModel> albums) {
    if (albums.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.photo_album_outlined, size: 64.r, color: Colors.grey),
            SizedBox(height: 16.h),
            Text(
              '暂无相册',
              style: TextStyle(fontSize: 16.sp, color: Colors.grey),
            ),
            SizedBox(height: 16.h),
            ElevatedButton.icon(
              onPressed: () => _showCreateAlbumDialog(context, ref),
              icon: const Icon(Icons.add),
              label: const Text('创建相册'),
              style: ElevatedButton.styleFrom(
                backgroundColor: AppTheme.primaryColor,
                foregroundColor: Colors.white,
              ),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: () async {
        ref.invalidate(albumsProvider);
      },
      child: GridView.builder(
        padding: EdgeInsets.all(16.r),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: MediaQuery.of(context).size.width > 600 ? 3 : 2,
          crossAxisSpacing: 16.r,
          mainAxisSpacing: 16.r,
          childAspectRatio: 0.8,
        ),
        itemCount: albums.length,
        itemBuilder: (context, index) {
          final album = albums[index];
          return AlbumGridItem(
            album: album,
            onTap: () => _navigateToAlbumDetail(context, ref, album),
            onEdit: () => _showEditAlbumDialog(context, ref, album),
            onDelete: () => _showDeleteAlbumDialog(context, ref, album),
          );
        },
      ),
    );
  }

  /// 显示创建相册对话框
  void _showCreateAlbumDialog(BuildContext context, WidgetRef ref) {
    showDialog(
      context: context,
      builder: (context) => CreateAlbumDialog(
        onSubmit: (name, description) async {
          Navigator.of(context).pop();
          await ref
              .read(albumOperationProvider.notifier)
              .createAlbum(name, description: description);
        },
      ),
    );
  }

  /// 显示编辑相册对话框
  void _showEditAlbumDialog(
      BuildContext context, WidgetRef ref, AlbumModel album) {
    showDialog(
      context: context,
      builder: (context) => CreateAlbumDialog(
        title: '编辑相册',
        initialName: album.name,
        initialDescription: album.description,
        submitButtonText: '保存',
        onSubmit: (name, description) async {
          Navigator.of(context).pop();
          await ref.read(albumOperationProvider.notifier).updateAlbum(
                album.id,
                name: name,
                description: description,
              );
        },
      ),
    );
  }

  /// 显示删除相册确认对话框
  void _showDeleteAlbumDialog(
      BuildContext context, WidgetRef ref, AlbumModel album) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除相册'),
        content: Text('确定要删除相册「${album.name}」吗？此操作不可恢复，相册中的所有照片将被删除。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.of(context).pop();
              await ref
                  .read(albumOperationProvider.notifier)
                  .deleteAlbum(album.id);
            },
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  /// 导航到相册详情页
  void _navigateToAlbumDetail(
      BuildContext context, WidgetRef ref, AlbumModel album) {
    ref.read(selectedAlbumIdProvider.notifier).state = album.id;
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => AlbumDetailScreen(albumId: album.id),
      ),
    );
  }

  /// 显示操作状态提示
  void _showOperationMessage(BuildContext context, AlbumOperationState state) {
    if (state.isSuccess && state.message != null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(state.message!)),
        );
      });
    } else if (!state.isSuccess && state.error != null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(state.error!),
            backgroundColor: Colors.red,
          ),
        );
      });
    }
  }
}
